<?php


namespace App\Rpc\client\impl;

use App\Common\Res;
use App\Common\StringUtils;
use App\Constants\ConstCode;
use App\Constants\ErrorCode;
use App\Model\AdminUser;
use App\Model\Seller;
use App\Request\client\SellerRequest;
use App\Rpc\client\SellerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Hyperf\Context\Context;
use Psr\Http\Message\ServerRequestInterface;


class SellerImpl implements SellerInterface
{
    use StringUtils, Res;

    /**
     * 设备登录
     * @param array $params
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function login(array $params): array
    {
        ApplicationContext::getContainer()->get(SellerRequest::class)->validated($params, __FUNCTION__);
        return Db::transaction(function () use ($params) {
            $seller = Seller::where(['number' => trim($params['number']), 'password' => trim($params['password'])])->first();
            $versionNo = $this->getSettingContent('versionNo');
            if (empty($seller))
                return $this->Error(ErrorCode::ERROR, "登录信息错误");
            if ($seller['status'] == ConstCode::STATUS_NO)
                return $this->Error(ErrorCode::ERROR, "已被禁用,请联系客服");
            if (floatval($params['versionNo']) < floatval($versionNo))
                return $this->Error(ErrorCode::ERROR, "apk版本过低,请联系客服升级");
            $token = $this->basic_token(trim($params['number']), trim($params['password']));
            $seller->token = $token;
            $result = $seller->save();
            return $this->Success('登录成功', ['token' => $token]);
        });
    }

    /**
     * 获取商户余额
     * @param array $params
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getSellerBalance(array $params): array
    {
        $seller = Context::get(ServerRequestInterface::class)->getAttribute('seller');
        // 同样，记得解码 JSON 字符串
        $sellerArr = json_decode($seller, true);
        $balance = !empty($sellerArr) ? intval($sellerArr['balance']) : 0;
        if ($balance > 0) {
            return $this->Success('获取剩余点数成功', ['count' => $balance]);
        } else {
            return $this->Error(ErrorCode::ERROR, "点数不足，请联系客服；付费后可继续找回码号");
        }

    }


}